# -*- encoding: utf-8 -*-
import os
import time
import datetime
from mylib_utils import *
from mylib_db import *

"""
1. 运行数据备份
2. 获取备份的数据条数
3. 保存到数据表
使用：
前台界面加载最后一次备份的数据信息，包括备份时间 + 备份条数
"""
# 定义服务器，用户名、密码、数据库名称（多个库分行放置）和备份的路径
# DB_HOST = 'rm-bp151dcc75aycqd80to.mysql.rds.aliyuncs.com'
# DB_USER = 'measurement'
# DB_USER_PASSWD = 'Measure123'

# 数据库设置（本地设置）
DB_HOST = '127.0.0.1'
DB_USER = 'root'
DB_USER_PASSWD = '123456'

DB_NAME = 'dbbackup/dbnames.txt'
# BACKUP_PATH = '/mnt/dbbackup/mysql/'
DB_CHARSET = "utf8mb4"
# BACKUP_PATH = 'dbbackup/'
BACKUP_PATH = '../../db_backup/dbbackup/'
TODAYBACKUPPATH = ''
DATETIME = ''
SQLFILENAME = ''        # 目录中只有一个文件时生效

# 备份信息
# 备份操作记录插入的数据库表
BackupInfoDbTable = "sys_db_backup_info"
BackupStartTime = ''
BackupEndTime = ''

# 定义执行备份脚本，读取文件中的数据库名称，注意按行读写，不校验是否存在该库
def run_backup():
    global SQLFILENAME
    in_file = open(DB_NAME, "r")
    for dbname in in_file.readlines():
        dbname = dbname.strip()
        print("now starting backup database %s" % dbname)
        # dumpcmd = "mysqldump -u" + DB_USER + " -p" + DB_USER_PASSWD + " " + dbname + " > " + TODAYBACKUPPATH + "/" + dbname + ".sql"
        dumpcmd = "mysqldump -h%s -u%s -p%s %s --default_character-set=%s > %s/%s_%s.sql" % \
                  (DB_HOST, DB_USER, DB_USER_PASSWD, dbname, DB_CHARSET, TODAYBACKUPPATH, DATETIME, dbname)
        print(dumpcmd)
        os.system(dumpcmd)

    SQLFILENAME = "%s/%s_%s.sql" % (TODAYBACKUPPATH, DATETIME, dbname)      # 目录中只有一个文件时生效
    in_file.close()


# 执行压缩的函数
def run_tar():
    compress_file = TODAYBACKUPPATH + ".tar.gz"
    compress_cmd = "tar -czvf " + compress_file + " " + TODAYBACKUPPATH
    print("compress command: %s" % compress_cmd)
    #os.chdir(BACKUP_PATH)
    os.system("pwd")
    os.system(compress_cmd)
    print("compress complete!")
    # 删除备份文件夹
    remove_cmd = "rm -rf "+TODAYBACKUPPATH
    os.system(remove_cmd)


def run_tar_win():
    """
    Windows下压缩和解压命令：
    makecab e:/test.txt e:/test.zip
    expand e:/test.zip e:/test.txt
    参考：http://blog.haoji.me/windows-cmd-zip.html
    """
    compress_file = TODAYBACKUPPATH + ".zip"
    # compress_cmd = "makecab " + TODAYBACKUPPATH + " " + compress_file
    compress_cmd = "makecab " + SQLFILENAME + " " + compress_file
    print("compress command: %s" % compress_cmd)
    os.chdir(BACKUP_PATH)
    os.system(compress_cmd)
    print("compress complete!")
    print("unzip command: expand compressed_file.zip target_name.sql")
    # 删除备份文件夹
    remove_cmd = "del "+TODAYBACKUPPATH
    os.system(remove_cmd)


def run_db_backup():
    global BackupStartTime, DATETIME, TODAYBACKUPPATH, BackupEndTime

    BackupStartTime = get_current_time()
    DATETIME = time.strftime('%Y%m%d-%H%M%S')
    TODAYBACKUPPATH = BACKUP_PATH + DATETIME
    print(BackupStartTime)
    print(DATETIME)
    print(TODAYBACKUPPATH)

    print("createing backup folder!")
    # 创建备份文件夹
    if not os.path.exists(TODAYBACKUPPATH):
        os.makedirs(TODAYBACKUPPATH)

    print("checking for databases names file")

    # 备份数据库文件存在就执行备份和压缩，否则退出
    if os.path.exists(DB_NAME):
        # file1 = open(DB_NAME)
        print("starting backup of all db listed in file "+DB_NAME)
        run_backup()
        ret = checkLinuxOrWindows()
        if ret == 2:
            print("Windows环境压缩备份文件")
            run_tar_win()
        else:
            print("Linux环境压缩备份文件")
            run_tar()

        print("backup success!")
    else:
        print("database file not found..")
        # exit()

    BackupEndTime = get_current_time()

    return 0


def get_data_count():
    # db_count_tables_list = ["bt_data", "bt_data_l0", "bt_data_l0_raw", "bt_data_l2_raw"]
    # 只记录文件数量
    db_count_tables_list = ["bt_data_head"]
    sum = 0
    for table in db_count_tables_list:
        if table == "bt_data_head":
            count = count_db_data_lines(table, "level=1")
        else:
            count = count_db_data_lines(table)
        print(count)
        sum += count_db_data_lines(table)

    print(sum)
    return sum


def save_backup_info():
    """
    备份信息插入数据库备份信息表
    """
    col_str = 'BackupStartTime, BackupEndTime, DataCount'
    data_count = get_data_count()
    value_str = '"%s", "%s", "%d"' % (BackupStartTime, BackupEndTime, data_count)

    print("插入数据库备份信息： %s" % value_str)
    head_id = insert_db(BackupInfoDbTable, col_str, value_str)
    print("数据库备份信息表插入ID： %d" % head_id)
    if head_id == -1:
        # print("[Error]：数据库备份信息插入错误！")
        return "[Error]：数据库备份信息插入错误！"

    print("数据库备份信息，插入表项id: %d" % head_id )

    # 保存数据备份记录到日志信息
    full_path = TODAYBACKUPPATH + ".tar.gz"
    arr = full_path.split('/')
    backup_file = arr[-1]
    run_time = get_interview_v2(BackupStartTime, BackupEndTime)     # 单位：ms
    operate_result = "db_backup/dbbackup/%s" % backup_file
    saveSysLog(2, "数据库备份", operate_result, run_time)

    # saveReadFileLog(2, "db_backup/dbbackup/", backup_file, -1, "", 0, run_time)
    return head_id


def saveSysLog(OperateStaff, OperateType, OperateResult, LastTime):
    """
    日志存储功能
    """
    sys_log_table = "bt_sys_op_log"
    value_str = '"%d", "%s", "%s", "%d"' % (OperateStaff, OperateType, OperateResult, LastTime)
    print("读文件log： %s" % value_str)
    insert_db(sys_log_table, "OperateStaff, OperateType, OperateResult, LastTime", value_str)
    print("保存读取文件记录完成！")


# 此函数废弃不用，数据备份记录存入log表
def saveReadFileLog(OperateStaff, DataPath, FileName, DeviceId, DeviceName, IsAbnormal, LastTime=0, DataCount=0, AbnormalInfo=""):
    """
    操作人、数据路径、文件名称、设备Id、设备名称、是否异常、异常原因
    """
    readFileLogTable = "bt_data_read_log"
    value_str = '"%d", "%s", "%s", "%d", "%s", "%d", "%s", "%d", "%d"' % (OperateStaff, DataPath, FileName, DeviceId, DeviceName, IsAbnormal, AbnormalInfo, LastTime, DataCount)
    print("读文件log： %s" % value_str)
    ret = insert_db(readFileLogTable, "OperateStaff, DataPath, FileName, DeviceId, DeviceName, IsAbnormal, AbnormalInfo, LastTime, DataCount", value_str)
    print(ret)
    print("保存读取文件记录完成！")


if __name__ == '__main__':
    print("备份开始..")
    run_db_backup()
    print("备份结束..")
    print("记录备份数据到数据库开始..")
    save_backup_info()
    print("记录备份数据到数据库结束..")
